Public Class frmMain
    Dim uninstallLog As String

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        If MsgBox("Are you sure you want to exit without uninstalling?", MsgBoxStyle.YesNoCancel + MsgBoxStyle.DefaultButton2, "Exit Confirmation") = MsgBoxResult.Yes Then
            Application.Exit()
        End If
    End Sub

    Private Sub btnUninstall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUninstall.Click
        Dim uninstallFile As IO.TextReader
        Dim otherUninstalls As IO.TextReader
        Dim selfDeleter As IO.TextWriter
        Dim selfDelete As Boolean = False
        Dim otherUninstallFiles As String = ""
        Dim safeToRemove As Boolean
        Dim others() As String
        Dim fileCnt As Integer = 0
        Dim regCnt As Integer = 0
        Dim regs() As String
        Dim files() As String
        Dim parts() As String
        Dim line As String
        Dim i As Integer
        Dim j As Integer
        Dim procs() As Diagnostics.Process

        btnExit.Enabled = False
        btnUninstall.Enabled = False

        'read install log
        uninstallFile = IO.File.OpenText(uninstallLog)
        line = uninstallFile.ReadLine
        If Split(line, ":")(0) = "files" Then
            fileCnt = Split(line, ":")(1)
        Else
            regCnt = Split(line, ":")(1)
        End If
        line = uninstallFile.ReadLine
        If Split(line, ":")(0) = "files" Then
            fileCnt = Split(line, ":")(1)
        Else
            regCnt = Split(line, ":")(1)
        End If

        ReDim files(fileCnt)
        ReDim regs(regCnt)
        For i = 0 To fileCnt - 1
            files(i) = uninstallFile.ReadLine
        Next
        For i = 0 To regCnt - 1
            regs(i) = uninstallFile.ReadLine
        Next
        uninstallFile.Close()

        'remove registry entries
        lblReg.ForeColor = Color.Tomato
        'do remove
        For i = 0 To regCnt - 1
            parts = Split(regs(i), "::")
            If parts(0) = "HKLM" Then
                Microsoft.Win32.Registry.LocalMachine.OpenSubKey(parts(1), True).DeleteValue(parts(2))
            End If
        Next
        'done removing registry entries
        lblReg.ForeColor = Color.LimeGreen
        chkReg.Checked = True

        'remove files/directories
        lblFiles.ForeColor = Color.Tomato
        If IO.Path.GetFileNameWithoutExtension(uninstallLog) = "uninstallServer" Then
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallClient.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallClient.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallAdmin.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallAdmin.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
        ElseIf IO.Path.GetFileNameWithoutExtension(uninstallLog) = "uninstallClient" Then
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallServer.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallServer.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallAdmin.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallAdmin.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
        ElseIf IO.Path.GetFileNameWithoutExtension(uninstallLog) = "uninstallAdmin" Then
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallClient.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallClient.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
            If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallServer.log") Then
                otherUninstalls = IO.File.OpenText(IO.Path.GetDirectoryName(uninstallLog) & "\uninstallServer.log")
                otherUninstallFiles = otherUninstallFiles & ControlChars.CrLf & otherUninstalls.ReadToEnd
                otherUninstalls.Close()
            End If
        End If
        otherUninstallFiles = otherUninstallFiles.ToLower()
        others = Split(otherUninstallFiles, ControlChars.CrLf)
        'do remove
        For i = 0 To fileCnt - 1
            safeToRemove = True
            For j = 0 To others.Length - 1
                If files(i).ToLower = others(j) Then safeToRemove = False
            Next
            If safeToRemove Then
                If IO.Path.GetExtension(files(i)) = ".exe" Then
                    procs = Diagnostics.Process.GetProcesses
                    For j = 0 To procs.Length - 1
                        If procs(j).ProcessName.ToLower = IO.Path.GetFileNameWithoutExtension(files(i)).ToLower Then
                            procs(j).Kill()
                            Threading.Thread.Sleep(1000)
                        End If
                    Next
                End If
                Try
                    IO.File.Delete(files(i))
                Catch
                End Try
            End If
        Next
        If IO.File.Exists(IO.Path.GetDirectoryName(uninstallLog) & "\" & IO.Path.GetFileNameWithoutExtension(uninstallLog).Substring(9) & "Config.xml") Then IO.File.Delete(IO.Path.GetDirectoryName(uninstallLog) & "\" & IO.Path.GetFileNameWithoutExtension(uninstallLog).Substring(9) & "Config.xml")
        'done removing files
        lblFiles.ForeColor = Color.LimeGreen
        chkFiles.Checked = True

        'do final cleanup
        lblCleanup.ForeColor = Color.Tomato
        'do registry cleanup
        For i = 0 To regCnt - 1
            parts = Split(regs(i), "::")
            If parts(0) = "HKLM" Then
                If Microsoft.Win32.Registry.LocalMachine.OpenSubKey(parts(1), True).ValueCount = 0 Then
                    Microsoft.Win32.Registry.LocalMachine.DeleteSubKey(parts(1), True)
                End If
            End If
        Next
        'do filesystem cleanup
        IO.File.Delete(uninstallLog)
        For Each fileFound As String In IO.Directory.GetFiles(Application.StartupPath, "debug_ern_" & IO.Path.GetFileNameWithoutExtension(uninstallLog).Substring(9) & "_*.txt")
            IO.File.Delete(fileFound)
        Next
        For i = 0 To fileCnt - 1
            Try
                If IO.Directory.Exists(IO.Path.GetDirectoryName(files(i))) Then
                    If IO.Directory.GetFiles(IO.Path.GetDirectoryName(files(i))).Length = 0 Then
                        IO.Directory.Delete(IO.Path.GetDirectoryName(files(i)))
                    End If
                End If
            Catch
            End Try
        Next
        If Not IO.File.Exists(Application.StartupPath & "\uninstallAdmin.log") Then
            If Not IO.File.Exists(Application.StartupPath & "\uninstallServer.log") Then
                If Not IO.File.Exists(Application.StartupPath & "\uninstallClient.log") Then
                    selfDeleter = IO.File.CreateText(Environment.SystemDirectory & "\ernDeleteMe.bat")
                    selfDeleter.WriteLine(":Repeat")
                    selfDeleter.WriteLine("del " & ControlChars.Quote & Application.ExecutablePath & ControlChars.Quote)
                    selfDeleter.WriteLine("if exist " & ControlChars.Quote & Application.ExecutablePath & ControlChars.Quote & "goto Repeat")
                    If IO.Directory.GetFiles(Application.StartupPath).Length = 1 Then
                        selfDeleter.WriteLine("rd " & ControlChars.Quote & Application.StartupPath & ControlChars.Quote)
                    End If
                    selfDeleter.WriteLine("del " & Environment.SystemDirectory & "\ernDeleteMe.bat" & ControlChars.CrLf)
                    selfDelete = True
                    selfDeleter.Flush()
                    selfDeleter.Close()
                End If
            End If
        End If
        'remove the program from the add/remove program list...
        Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", True).DeleteSubKey("ERN " & IO.Path.GetFileNameWithoutExtension(uninstallLog).Substring(9))
        'done doing the final cleanups
        lblCleanup.ForeColor = Color.LimeGreen
        chkCleanup.Checked = True
        'done!
        MsgBox("Uninstallation successful!", MsgBoxStyle.OkOnly, "Success")
        If selfDelete Then Diagnostics.Process.Start(Environment.SystemDirectory & "\ernDeleteMe.bat")
        Application.Exit()
    End Sub

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim doUninstall As Boolean = True
        Dim errText As String = ""

        If Environment.GetCommandLineArgs.Length > 1 Then
            If Not IO.File.Exists(Environment.GetCommandLineArgs(1)) Then
                If Not IO.File.Exists(Application.StartupPath & "\" & Environment.GetCommandLineArgs(1)) Then
                    errText = "not found"
                    doUninstall = False
                Else
                    uninstallLog = Application.StartupPath & "\" & Environment.GetCommandLineArgs(1)
                End If
            Else
                uninstallLog = Environment.GetCommandLineArgs(1)
            End If
        Else
            errText = "not specified"
            doUninstall = False
        End If

        If Not doUninstall Then
            MsgBox("Install log " & errText & "!  Please rerun with the install log as a command line argument (if ran from Add/Remove Programs than check the registry).")
            Application.Exit()
        Else
            If IO.Path.GetDirectoryName(uninstallLog) = "" Then uninstallLog = Application.StartupPath & "\" & uninstallLog
        End If
    End Sub
End Class
